package cn.lblbc.cootext

import android.net.Uri
import android.os.Bundle
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import android.content.Intent
import android.widget.TextView
import java.io.BufferedReader
import java.io.InputStreamReader
import android.widget.EditText
import android.widget.ImageButton
import android.view.View
import android.view.ViewGroup
import android.widget.HorizontalScrollView
import android.widget.LinearLayout
import com.google.android.material.floatingactionbutton.FloatingActionButton
import android.text.Editable
import android.text.TextWatcher
import android.widget.ScrollView
import android.text.SpannableString
import android.text.style.BackgroundColorSpan
import android.graphics.Color
import android.widget.Toast
import android.view.inputmethod.InputMethodManager
import android.content.Context
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.appcompat.app.AlertDialog
import androidx.drawerlayout.widget.DrawerLayout
import com.google.android.material.navigation.NavigationView

class MainActivity : AppCompatActivity() {
    private lateinit var textView: TextView
    private lateinit var searchEditText: EditText
    private lateinit var searchLayout: LinearLayout
    private lateinit var defaultSearchLayout: LinearLayout
    private lateinit var inputSearchLayout: LinearLayout
    private lateinit var resultSearchLayout: LinearLayout
    private lateinit var scrollView: ScrollView
    private lateinit var historyRecyclerView: RecyclerView
    private lateinit var historyFooter: LinearLayout
    private lateinit var clearHistoryButton: TextView
    private lateinit var searchHistoryManager: SearchHistoryManager
    private lateinit var searchHistoryAdapter: SearchHistoryAdapter
    private lateinit var drawerLayout: DrawerLayout
    private lateinit var navigationView: NavigationView
    private lateinit var settingsManager: SettingsManager
    private lateinit var instructionText: TextView
    private var searchTextList = mutableListOf<Int>()
    private var currentSearchIndex = -1
    
    // 标签管理
    private lateinit var tabCount: TextView
    private lateinit var exportTextView: TextView
    private lateinit var exportScrollView: ScrollView
    private val tabs = mutableListOf<Pair<String, String>>() // Pair<标题, 内容>
    private var currentTabIndex = 0
    
    // 搜索UI状态
    private enum class SearchUIState {
        DEFAULT,    // 默认状态：只显示搜索图标
        INPUT,      // 输入状态：显示输入框和关闭图标
        RESULT      // 搜索结果状态：显示搜索图标、上一处、下一处图标和关闭图标
    }
    
    private var currentSearchUIState = SearchUIState.DEFAULT

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
        
        settingsManager = SettingsManager(this)
        
        initViews()
        setupSearchFunctionality()
        
        // 处理其他应用分享过来的内容
        handleIncomingContent(intent)
        
        // 初始化第一个标签（原始内容）
        tabs.add("原始内容" to textView.text.toString())
        updateTabBar()
        updateTextWrapping()
        
        // 检查是否有内容显示，如果没有则显示提示信息
        checkAndShowInstruction()
    }
    
    private fun openFilePicker() {
        val intent = Intent(Intent.ACTION_OPEN_DOCUMENT).apply {
            addCategory(Intent.CATEGORY_OPENABLE)
            type = "*/*"
        }
        startActivityForResult(intent, FILE_PICKER_REQUEST_CODE)
    }
    
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == FILE_PICKER_REQUEST_CODE && resultCode == RESULT_OK) {
            data?.data?.also { uri ->
                handleIncomingFile(uri)
            }
        }
    }
    
    companion object {
        private const val FILE_PICKER_REQUEST_CODE = 1001
    }
    
    private fun initViews() {
        textView = findViewById(R.id.textView)
        searchEditText = findViewById(R.id.searchEditText)
        searchLayout = findViewById(R.id.searchLayout)
        defaultSearchLayout = findViewById(R.id.defaultSearchLayout)
        inputSearchLayout = findViewById(R.id.inputSearchLayout)
        resultSearchLayout = findViewById(R.id.resultSearchLayout)
        scrollView = findViewById(R.id.scrollView)
        historyRecyclerView = findViewById(R.id.historyRecyclerView)
        historyFooter = findViewById(R.id.historyFooter)
        clearHistoryButton = findViewById(R.id.clearHistoryButton)
        drawerLayout = findViewById(R.id.drawerLayout)
        navigationView = findViewById(R.id.navigationView)
        instructionText = findViewById(R.id.instructionText)
        
        val openFileFab: FloatingActionButton = findViewById(R.id.openFileFab)
        openFileFab.setOnClickListener {
            openFilePicker()
        }
        
        val menuButton: ImageButton = findViewById(R.id.menuButton)
        val menuButtonInResult: ImageButton = findViewById(R.id.menuButtonInResult)
        val searchIconButton: ImageButton = findViewById(R.id.searchIconButton)
        val searchIconButtonInResult: ImageButton = findViewById(R.id.searchIconButtonInResult)
        val prevButton: ImageButton = findViewById(R.id.prevButton)
        val nextButton: ImageButton = findViewById(R.id.nextButton)
        val closeSearchButton: ImageButton = findViewById(R.id.closeSearchButton)
        val closeSearchButtonInResult: ImageButton = findViewById(R.id.closeSearchButtonInResult)
        
        // 初始化搜索历史管理器
        searchHistoryManager = SearchHistoryManager(this)
        
        // 初始化RecyclerView
        historyRecyclerView.layoutManager = LinearLayoutManager(this)
        searchHistoryAdapter = SearchHistoryAdapter(
            searchHistoryManager.getSearchHistory().toMutableList(),
            onItemClickListener = { query ->
                searchEditText.setText(query)
                searchEditText.setSelection(query.length)
                hideHistoryView()
                hideKeyboard()  // 关闭软键盘
                // 使用findNext来触发搜索，这样如果没找到会显示Toast
                findNext()
            },
            onDeleteClickListener = { query, position ->
                searchHistoryManager.removeSearchQuery(query)
                updateHistoryView()
            }
        )
        historyRecyclerView.adapter = searchHistoryAdapter
        
        // 设置清空历史按钮点击事件
        clearHistoryButton.setOnClickListener {
            searchHistoryManager.clearSearchHistory()
            updateHistoryView()
        }
        
        // 初始化标签计数
        tabCount = findViewById(R.id.tabCount)
        val tabCountInResult: TextView = findViewById(R.id.tabCountInResult)
        exportTextView = findViewById(R.id.exportTextView)
        exportScrollView = findViewById(R.id.exportScrollView)
        
        // 标签数量点击事件
        tabCount.setOnClickListener {
            showTabSelectionDialog()
        }
        
        tabCountInResult.setOnClickListener {
            showTabSelectionDialog()
        }
        
        // 菜单按钮点击事件
        menuButton.setOnClickListener {
            drawerLayout.openDrawer(navigationView)
        }
        
        menuButtonInResult.setOnClickListener {
            drawerLayout.openDrawer(navigationView)
        }
        
        // 默认状态下的搜索图标点击事件
        searchIconButton.setOnClickListener {
            switchToInputState()
        }
        
        // 结果状态下的搜索图标点击事件
        searchIconButtonInResult.setOnClickListener {
            switchToInputState()
        }
        
        // 导出按钮点击事件
        val exportButton: ImageButton = findViewById(R.id.exportButton)
        exportButton.setOnClickListener {
            exportMatchingLines()
        }
        
        prevButton.setOnClickListener {
            hideKeyboard()
            findPrevious()
        }
        
        nextButton.setOnClickListener {
            hideKeyboard()
            findNext()
        }
        
        closeSearchButton.setOnClickListener {
            hideSearchLayout()
        }
        
        closeSearchButtonInResult.setOnClickListener {
            hideSearchLayout()
        }
        
        // 抽屉菜单项点击事件
        navigationView.setNavigationItemSelectedListener { menuItem ->
            when (menuItem.itemId) {
                R.id.nav_settings -> {
                    val intent = Intent(this, SettingsActivity::class.java)
                    startActivity(intent)
                    drawerLayout.closeDrawers()
                    true
                }
                else -> {
                    drawerLayout.closeDrawers()
                    true
                }
            }
        }
        
        // 搜索框获取焦点时显示历史记录
        searchEditText.setOnFocusChangeListener { _, hasFocus ->
            if (hasFocus) {
                updateHistoryView()
            }
        }
        
        // 搜索框点击时显示历史记录
        searchEditText.setOnClickListener {
            updateHistoryView()
        }
    }
    
    private fun setupSearchFunctionality() {
        searchEditText.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
            
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                if (!s.isNullOrBlank()) {
                    // 只清除高亮和准备搜索，但不显示Toast提示
                    clearSearchHighlights()
                    searchTextList.clear()
                    currentSearchIndex = -1
                    
                    // 如果用户正在输入，隐藏历史记录
                    if (count > 0) {
                        hideHistoryView()
                    }
                } else {
                    clearSearchHighlights()
                    // 如果搜索框为空，显示历史记录
                    updateHistoryView()
                }
            }
            
            override fun afterTextChanged(s: Editable?) {}
        })
        
        // 添加搜索动作监听
        searchEditText.setOnEditorActionListener { _, actionId, _ ->
            if (actionId == android.view.inputmethod.EditorInfo.IME_ACTION_SEARCH) {
                val query = searchEditText.text.toString()
                if (query.isNotBlank()) {
                    // 保存搜索记录
                    searchHistoryManager.addSearchQuery(query)
                    hideHistoryView()
                    hideKeyboard()  // 隐藏软键盘
                    findNext()
                    return@setOnEditorActionListener true
                }
            }
            false
        }
    }
    
    private fun switchToDefaultState() {
        currentSearchUIState = SearchUIState.DEFAULT
        defaultSearchLayout.visibility = View.VISIBLE
        inputSearchLayout.visibility = View.GONE
        resultSearchLayout.visibility = View.GONE
        hideHistoryView()
    }
    
    private fun switchToInputState() {
        currentSearchUIState = SearchUIState.INPUT
        defaultSearchLayout.visibility = View.GONE
        inputSearchLayout.visibility = View.VISIBLE
        resultSearchLayout.visibility = View.GONE
        searchEditText.requestFocus()
        updateHistoryView()
        
        // 显示软键盘
        val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.showSoftInput(searchEditText, InputMethodManager.SHOW_IMPLICIT)
    }
    
    private fun switchToResultState() {
        currentSearchUIState = SearchUIState.RESULT
        defaultSearchLayout.visibility = View.GONE
        inputSearchLayout.visibility = View.GONE
        resultSearchLayout.visibility = View.VISIBLE
        hideHistoryView()
    }
    
    private fun hideSearchLayout() {
        switchToDefaultState()
        clearSearchHighlights()
        currentSearchIndex = -1
        searchTextList.clear()
        // 保持标签栏显示不变
    }
    
    private fun updateHistoryView() {
        val historyList = searchHistoryManager.getSearchHistory()
        if (historyList.isNotEmpty()) {
            searchHistoryAdapter.updateData(historyList)
            historyRecyclerView.visibility = View.VISIBLE
            historyFooter.visibility = View.VISIBLE
        } else {
            historyRecyclerView.visibility = View.GONE
            historyFooter.visibility = View.GONE
        }
    }
    
    private fun hideHistoryView() {
        historyRecyclerView.visibility = View.GONE
        historyFooter.visibility = View.GONE
    }
    
    private fun findAllOccurrences(searchText: String) {
        // 清除之前的高亮显示
        clearSearchHighlights()
        
        searchTextList.clear()
        val content = if (currentTabIndex == 0) {
            textView.text.toString()
        } else {
            exportTextView.text.toString()
        }
        
        if (searchText.isEmpty()) return
        
        var startIndex = 0
        while (true) {
            val index = content.indexOf(searchText, startIndex, ignoreCase = true)
            if (index == -1) {
                break
            }
            searchTextList.add(index)
            startIndex = index + 1
        }
        
        currentSearchIndex = -1
    }
    
    private fun clearSearchHighlights() {
        // 清除之前的高亮显示（同时清除两个TextView的高亮）
        val textViews = listOf(textView, exportTextView)
        textViews.forEach { tv ->
            val text = tv.text
            if (text is SpannableString) {
                val spans = text.getSpans(0, text.length, BackgroundColorSpan::class.java)
                for (span in spans) {
                    text.removeSpan(span)
                }
            } else {
                tv.text = SpannableString(text)
            }
        }
    }
    
    private fun findNext() {
        val searchText = searchEditText.text.toString()
        if (searchText.isNotBlank()) {
            // 保存搜索记录
            searchHistoryManager.addSearchQuery(searchText)
            
            if (searchTextList.isEmpty()) {
                findAllOccurrences(searchText)
            }
            
            if (searchTextList.isNotEmpty()) {
                // 切换到结果状态
                switchToResultState()
                
                currentSearchIndex = (currentSearchIndex + 1) % searchTextList.size
                scrollToPosition(searchTextList[currentSearchIndex])
            } else {
                // 如果没有找到匹配项，显示Toast提示
                Toast.makeText(this, "未找到\"$searchText\"", Toast.LENGTH_SHORT).show()
            }
        }
    }
    
    private fun findPrevious() {
        val searchText = searchEditText.text.toString()
        if (searchText.isNotBlank()) {
            // 保存搜索记录
            searchHistoryManager.addSearchQuery(searchText)
            
            if (searchTextList.isEmpty()) {
                findAllOccurrences(searchText)
            }
            
            if (searchTextList.isNotEmpty()) {
                // 切换到结果状态
                switchToResultState()
                
                currentSearchIndex = if (currentSearchIndex <= 0) searchTextList.size - 1 else currentSearchIndex - 1
                scrollToPosition(searchTextList[currentSearchIndex])
            } else {
                // 如果没有找到匹配项，显示Toast提示
                Toast.makeText(this, "未找到\"$searchText\"", Toast.LENGTH_SHORT).show()
            }
        }
    }
    
    private fun scrollToPosition(position: Int) {
        // 滚动到指定位置
        val targetScrollView = if (currentTabIndex == 0) scrollView else exportScrollView
        val targetTextView = if (currentTabIndex == 0) textView else exportTextView
        
        targetTextView.post {
            val layout = targetTextView.layout
            if (layout != null && position < targetTextView.text.length) {
                val line = layout.getLineForOffset(position)
                val y = layout.getLineTop(line)
                targetScrollView.scrollTo(0, y)
                
                // 高亮显示找到的文本
                highlightText(position, searchEditText.text.length)
            }
        }
    }
    
    private fun highlightText(start: Int, length: Int) {
        val targetTextView = if (currentTabIndex == 0) textView else exportTextView
        val spannableString = SpannableString(targetTextView.text)
        // 清除之前的高亮
        spannableString.removeSpan(BackgroundColorSpan(Color.YELLOW))
        // 添加新的高亮
        spannableString.setSpan(
            BackgroundColorSpan(Color.YELLOW),
            start,
            start + length,
            SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE
        )
        targetTextView.text = spannableString
    }
    
    private fun exportMatchingLines() {
        val searchText = searchEditText.text.toString()
        if (searchText.isBlank()) {
            Toast.makeText(this, "请输入搜索内容", Toast.LENGTH_SHORT).show()
            return
        }
        
        val fullText = textView.text.toString()
        val lines = fullText.lines()
        val matchingLines = lines.filter { it.contains(searchText, ignoreCase = true) }
        
        if (matchingLines.isEmpty()) {
            Toast.makeText(this, "没有找到匹配的行", Toast.LENGTH_SHORT).show()
            return
        }
        
        val exportedContent = matchingLines.joinToString("\n")
        addTab("包含\"$searchText\"的行", exportedContent)
    }
    
    private fun addTab(title: String, content: String) {
        tabs.add(title to content)
        currentTabIndex = tabs.size - 1
        showTab(currentTabIndex)
        updateTabBar()
    }
    
    private fun showTab(index: Int) {
        if (index == 0) {
            // 显示原始内容
            scrollView.visibility = View.VISIBLE
            exportScrollView.visibility = View.GONE
        } else {
            // 显示导出内容
            scrollView.visibility = View.GONE
            exportScrollView.visibility = View.VISIBLE
            exportTextView.text = tabs[index].second
        }
        currentTabIndex = index
        updateTextWrapping()
    }
    
    private fun updateTabBar() {
        if (tabs.size > 1) {
            tabCount.visibility = View.VISIBLE
            tabCount.text = "${tabs.size}"
            // 同时更新结果状态下的标签计数
            val tabCountInResult: TextView = findViewById(R.id.tabCountInResult)
            tabCountInResult.visibility = View.VISIBLE
            tabCountInResult.text = "${tabs.size}"
        } else {
            tabCount.visibility = View.GONE
            // 同时隐藏结果状态下的标签计数
            val tabCountInResult: TextView = findViewById(R.id.tabCountInResult)
            tabCountInResult.visibility = View.GONE
        }
    }
    
    private fun showTabSelectionDialog() {
        val items = tabs.mapIndexed { index, pair -> 
            "${if (index == currentTabIndex) "✓ " else ""}${pair.first}" 
        }.toTypedArray()
        
        AlertDialog.Builder(this)
            .setTitle("选择标签")
            .setItems(items) { _, which ->
                showTab(which)
            }
            .show()
    }
    
    private fun closeCurrentTab() {
        if (tabs.size <= 1) return
        
        tabs.removeAt(currentTabIndex)
        if (currentTabIndex >= tabs.size) {
            currentTabIndex = tabs.size - 1
        }
        showTab(currentTabIndex)
        updateTabBar()
    }
    
    // 当Activity已经运行时，处理新的intent
    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        // 更新当前Activity的intent
        setIntent(intent)
        // 处理分享过来的内容
        handleIncomingContent(intent)
    }
    
    override fun onResume() {
        super.onResume()
        // 当返回到主界面时，更新文本换行设置
        updateTextWrapping()
    }
    
    private fun updateTextWrapping() {
        val isWrappingEnabled = settingsManager.isTextWrappingEnabled()
        textView.setHorizontallyScrolling(!isWrappingEnabled)
        exportTextView.setHorizontallyScrolling(!isWrappingEnabled)
        
        // 设置水平滚动条的可见性
        scrollView.setHorizontalScrollBarEnabled(!isWrappingEnabled)
        exportScrollView.setHorizontalScrollBarEnabled(!isWrappingEnabled)
        
        // 设置文本宽度
        if (isWrappingEnabled) {
            // 换行模式：文本宽度匹配父容器
            textView.layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT
            exportTextView.layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT
        } else {
            // 不换行模式：文本宽度自适应内容
            textView.layoutParams.width = ViewGroup.LayoutParams.WRAP_CONTENT
            exportTextView.layoutParams.width = ViewGroup.LayoutParams.WRAP_CONTENT
        }
        
        // 应用布局参数变更
        textView.requestLayout()
        exportTextView.requestLayout()
    }
    

    
    private fun handleIncomingContent(intent: Intent?) {
        val action = intent?.action
        val type = intent?.type
        
        // 检查是否是分享内容的intent
        if (Intent.ACTION_SEND == action && type != null) {
            // 获取分享的文本内容
            val sharedText = intent.getStringExtra(Intent.EXTRA_TEXT)
            if (sharedText != null) {
                // 显示分享的文本内容
                displayContent(sharedText)
                return
            }
            
            // 如果没有文本内容，则尝试获取分享的文件
            val uri = intent.getParcelableExtra<Uri>(Intent.EXTRA_STREAM)
            if (uri != null) {
                // 处理分享的文件
                handleIncomingFile(uri)
            }
        }
    }
    
    private fun handleIncomingFile(uri: Uri) {
        try {
            val inputStream = contentResolver.openInputStream(uri)
            val reader = BufferedReader(InputStreamReader(inputStream))
            val stringBuilder = StringBuilder()
            var line: String? = reader.readLine()
            while (line != null) {
                stringBuilder.append(line).append("\n")
                line = reader.readLine()
            }
            inputStream?.close()
            
            // 显示文件内容
            displayContent(stringBuilder.toString())
        } catch (e: Exception) {
            displayContent("无法读取文件: ${e.message}")
        }
    }
    
    private fun displayContent(content: String) {
        textView.text = content
        updateTextWrapping()
        // 内容显示后隐藏提示信息
        instructionText.visibility = View.GONE
    }
    
    private fun hideKeyboard() {
        // 获取输入法管理器
        val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        // 隐藏软键盘
        imm.hideSoftInputFromWindow(searchEditText.windowToken, 0)
    }
    
    private fun checkAndShowInstruction() {
        // 如果 textView 没有内容，则显示提示信息
        if (textView.text.isNullOrEmpty()) {
            instructionText.visibility = View.VISIBLE
        } else {
            instructionText.visibility = View.GONE
        }
    }
}